package com.fp.m7.dao;

import java.util.Date;
import java.util.List;

import com.fp.m7.model.Account;
import com.fp.m7.model.Comment;

public class CommentDaoImpl extends BaseDaoImpl<Comment> implements CommentDao {

    public CommentDaoImpl() {
        super(Comment.class);
    }

    @Override
    public List<Comment> findUsersLatestComments(Account account, int maxPerPage, int pageNo) {
        String query = "from Comment c where c.author = :author order by c.auditCD desc";
        return em.createQuery(query, Comment.class) //
                .setParameter("author", account) //
                .setMaxResults(maxPerPage) //
                .setFirstResult(pageNo * maxPerPage) //
                .getResultList();
    }

    @Override
    public List<Comment> findUsersCommentsByDate(Account account, Date from, Date to) {
        String query = "from Comment c where c.author = :author and c.auditCD >= :from and c.auditCD < :to order by c.auditCD desc";
        return em.createQuery(query, Comment.class) //
                .setParameter("author", account) //
                .setParameter("from", from) //
                .setParameter("to", to) //
                .getResultList();
    }

    @Override
    public List<Comment> findCommentFeedForUser(Account account, int maxPerPage, int pageNo) {       
        String query = "select c from Comment c " //
                        + "where c.author in " //
                            +"(select f.followed from Follow f " //
                             + "where f.follower = :account " //
                             + "and c.auditCD >= f.auditCD " //
                             +"and (c.auditCD < f.auditDD or f.auditDD is null) " //
                            + ") " //
                        + "order by c.auditCD desc";
        
        return em.createQuery(query, Comment.class) //
                .setParameter("account", account) //
                .setMaxResults(maxPerPage) //
                .setFirstResult(pageNo * maxPerPage) //
                .getResultList();
    }

    @Override
    public int removeUsersComments(Account account) {
        String query = "delete from Comment c where c.author = :author";
        return em.createQuery(query) //
                .setParameter("author", account) //
                .executeUpdate();
    }
}
